/*
 * @Author: yut
 * @Date: 2024-03-18 11:15:07
 * @LastEditors: lid lid@tiansu-china.com
 * @LastEditTime: 2024-06-27 14:33:47
 * @Descripttion:
 */
// http请求全局配置、请求、响应拦截

import Request, { type HttpRequestConfig, type HttpCustom, HttpError } from 'luch-request';

const http = new Request();
http.setConfig((config : any) => {
	/* 设置全局配置 */
	config.baseURL = '';
	return config;
});

// 请求之前拦截器。可以使用async await 做异步操作
http.interceptors.request.use(
	async (config : any) => {
		addHeader(config);
		return config;
	},
	(config : any) => {
		return Promise.reject(config);
	},
);

// 添加请求头信息
const addHeader = (config : any) => {
	const mergedObj = { ...config.header, ...getHeader() };
	config.header = mergedObj
	return config;
};

const FGetQueryParam = (key : string) => {
	const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
	const match = window.location.search.substring(1).match(reg) ?? '';
	if (match.length > 2) {
		return decodeURIComponent(match[2]);
	}
}
const getHeader = () => {
	return {
		"x-token": FGetQueryParam('token')
	};
}


// /* 响应之后拦截器。可以使用async await 做异步操作  */
http.interceptors.response.use(
	async (response : { data : any; statusCode : any; config : any; }) => {
		const data = response.data
		if (data.type && data.type != "success") {
			uni.hideLoading()
			uni.showToast({
				title: data.message,
				icon: 'error'
			})
		}
		return data;
	},
	async (error : any) => {
		const data = error.data
		if (data.type && data.type != "success") {
			uni.hideLoading()
			uni.showToast({
				title: data.message,
				icon: 'error'
			})
		}
		return Promise.reject(error);
	},
);


export { http, getHeader };